import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// import locale from 'element-ui/lib/locale/lang/en' // lang i18n

import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'

import flexible from 'amfe-flexible'

import {library} from '@fortawesome/fontawesome-svg-core'
import {fas} from '@fortawesome/free-solid-svg-icons'
import {far} from '@fortawesome/free-regular-svg-icons'
import {fab} from '@fortawesome/free-brands-svg-icons'
import {FontAwesomeIcon, FontAwesomeLayers, FontAwesomeLayersText}
  from '@fortawesome/vue-fontawesome'
library.add(fas, far, fab)
Vue.component('font-awesome-icon', FontAwesomeIcon)
Vue.component('font-awesome-layers', FontAwesomeLayers)
Vue.component('font-awesome-layers-text', FontAwesomeLayersText)


import '@/icons' // icon
import '@/permission' // permission control
import 'default-passive-events'
import VueJsonp from 'vue-jsonp'
Vue.use(VueJsonp)
/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
// if (process.env.NODE_ENV === 'production') {
//   const { mockXHR } = require('../mock')
//   mockXHR()
// }

import $ from 'jquery'
import Cookie from 'js-cookie'
import { TokenType } from '@/utils/enum'
var COS = require('cos-js-sdk-v5');
//--上传到腾讯cos
var Bucket;
var Region; /* 存储桶所在地域，必须字段 */
let CosAuth = null;
const baseURL = process.env.VUE_APP_BASE_API;

let getCosAuth = (callback) => {
	$.ajax({
		type: "GET",
		contentType: "application/json;charset=UTF-8",
		headers: {
			'Content-Type': 'application/json;charset=utf8',
			'Authorization':  'Bearer ' + Cookie.get(TokenType.USER_TOKEN)
		},
		url: baseURL + '/cos/getAuthorization',
		//后端接口返回临时秘钥信息
		data: null,
		//请求成功，这段是cos代码
		success: function(data) {
			if (!data) return console.error('credentials invalid');
      Bucket = data.bucket
      Region = data.region
			CosAuth = ({
				TmpSecretId: data.tmpSecretId,
				TmpSecretKey: data.tmpSecretKey,
				XCosSecurityToken: data.sessionToken,
				// 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
				StartTime: data.start_time, // 时间戳，单位秒，如：1580000000
				ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
			});

			callback()

		},
		//请求失败，包含具体的错误信息
		error: function(e) {
			console.log(e.status);
			console.log(e.responseText);
		}
	});
}


Vue.prototype.uploadOss = fileObj => {
    //重点，getAuthorization内部封装函数
    let getCosAuth2 = (options, callback) => {
	    callback(CosAuth)
    }
	getCosAuth(() => {
		var cos = new COS({
			getAuthorization: getCosAuth2//重点调用函数
		});
		var myDate = new Date();
		var ossPath = 'E2B/' + myDate.getFullYear() + "/" + (myDate.getMonth() + 1);
		// 获取文件后缀
		var pathArr = fileObj.file.name.split('.')
		//  随机生成文件名称
		var fileRandName = Date.now() + "" + parseInt(Math.random() * 1000)
		var fileName = fileRandName + '.' + pathArr[pathArr.length - 1]
		// 要提交的key
		var fileKey = ossPath + "/" + fileName;
		let formdata = {
			Bucket: Bucket,
			Region: Region,
			Key: fileKey,
			Body: fileObj.file,
			onTaskReady: function(tid) {

			},
			onHashProgress: function(progressData) {

			},
			onProgress: function(progressData) {

				if(fileObj.onProgress){
					fileObj.onProgress(progressData)
				}
			},
		}
		cos.putObject(formdata, function(err, data) {
			if (!err&&fileObj.onSuccess) {
				fileName = fileName.toLocaleLowerCase();
				//计算图片高度
				if (fileName.indexOf(".jpg") > 0 || fileName.indexOf(".jpeg") > 0 || fileName.indexOf(".png") > 0 || fileName
					.indexOf(".gif") > 0 || fileName.indexOf(".bmp") > 0) {
					var reader = new FileReader();
					reader.readAsDataURL(fileObj.file);
					reader.onload = function(theFile) {
						var image = new Image();
						image.src = theFile.target.result;
						image.onload = function() {
							fileObj.onSuccess({
								src: "https://" + data.Location,
								fileName: fileObj.file.name
							})
						};
					};
				} else {
					fileObj.onSuccess({
						src: "https://" + data.Location,
						fileName: fileObj.file.name
					})
				}
			}
		});
	})
}

// element-ui Select 选择器 滚动加载
import directives from './directives'
// 全局注册指令
Vue.use(directives)
// set ElementUI lang to EN
// Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui，按如下方式声明
Vue.use(ElementUI)

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
